using System;
using System.Collections.Generic;
using System.Text;

namespace Weever.Json.Binding
{
    class Stack<T>
        where T: IComparable
    {
        private List<T> _innerList;
        private int _topIndex;
        
        public Stack(int capacity)
        {
            _innerList = new List<T>(capacity);
            _topIndex = -1;
        }
        
        public void Push(T item)
        {
            _topIndex++;
            if (_topIndex < _innerList.Count)
                _innerList[_topIndex] = item;
            else 
                _innerList.Add(item);
        }
        
        public T Pop()
        {
            if (_topIndex < 0)
                throw new InvalidOperationException("Stack is empty");
            return _innerList[_topIndex--];
        }
        
        public T Peek()
        {
            if (_topIndex < 0)
                throw new InvalidOperationException("Stack is empty");
            return _innerList[_topIndex];
        }
        
        public void PopUntil(T untilItem)
        {
            for (; _topIndex >= 0; _topIndex--)
                if (_innerList[_topIndex].CompareTo(untilItem) == 0)
                    return;
        }

        public void PopAfter(T item)
        {
            PopUntil(item);
            if (_topIndex >= 0)
                Pop();
        }

        public bool TopIs(params T[] args)
        {
            if (_topIndex < 0)
                return false;

            T t = Peek();
            return Array.IndexOf(args, t) != -1;
        }

        public override string ToString()
        {
            StringBuilder buider = new StringBuilder();
            buider.Append("Stack");
            for (int i = 0; i <= _topIndex; i++)
                buider.AppendFormat("|{0}", _innerList[i]);

            return buider.ToString();
        }
    }
}
